﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace Light_Calendar
{
    public class EventsData
    {
        private string fileName;
        private SortedList<int, CalendarEvent> events;
        private int currentId;

        public List<CalendarEvent> Events { get { return events.Values.ToList(); } } 
        public delegate void UpdateEventHandler(CalendarEvent e);
        public event UpdateEventHandler Updating;
        public event UpdateEventHandler Updated;

        public EventsData(string dataFileName)
        {
            fileName = dataFileName;
            events = new SortedList<int, CalendarEvent>();
            currentId = 1;

            try
            {
                using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    XmlSerializer xmlFormat = new XmlSerializer(typeof(List<CalendarEvent>),
                        new Type[] { typeof(CalendarEvent) });
                    foreach (CalendarEvent e in (List<CalendarEvent>)xmlFormat.Deserialize(fStream))
                    {
                        events[e.Id] = e;
                        if (e.Id > currentId) currentId = e.Id;
                    }
                    currentId++;
                }
            }
            catch
            {
            }
        }

        public void Add(CalendarEvent e)
        {
            e.Id = currentId++;
            Updating(e);
            events[e.Id] = e;
            Updated(e);
        }
        
        public void Update(CalendarEvent e)
        {
            Updating(events[e.Id]);
            Updating(e);
            events[e.Id] = new CalendarEvent(e);
            Updated(e);
        }

        public void Remove(CalendarEvent e)
        {
            Updating(e);
            events.Remove(e.Id);
            Updated(null);
        }

        public void Save()
        {
            using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                XmlSerializer xmlFormat = new XmlSerializer(typeof(List<CalendarEvent>),
                    new Type[] { typeof(CalendarEvent) });
                xmlFormat.Serialize(fStream, Events);
            }
        }
    }
}
